Page({
  data: {
    imagePath: '',
    words: [],
    currentIndex: null,
    containerHeight: 0
  },

  onLoad(options) {
    const wordsData = JSON.parse(decodeURIComponent(options.wordsData || '[]'))
    const rpxRatio = wx.getSystemInfoSync().windowWidth / 750
    
    // 布局参数（rpx）
    const cardWidth = 260
    const gap = 50
    const startX = (750 - cardWidth * 2 - gap) / 2
    const startY = 80
    const verticalGap = 420
    const containerHeight = Math.ceil(wordsData.length / 2) * (240 + verticalGap) + startY * 2

    // 计算卡片位置
    const words = wordsData.map((word, index) => {
      const row = Math.floor(index / 2)
      const col = index % 2
      const x = (startX + col * (cardWidth + gap)) * rpxRatio
      const y = (startY + row * verticalGap) * rpxRatio

      return { ...word, x, y }
    })

    this.setData({
      imagePath: decodeURIComponent(options.imagePath || ''),
      words,
      containerHeight,
    })
  },

  playWord(e) {
    const word = e.currentTarget.dataset.word
    try {
      const innerAudioContext = wx.createInnerAudioContext()
      innerAudioContext.src = `https://dict.youdao.com/dictvoice?audio=${word}&type=1`

      innerAudioContext.onPlay(() => {
        console.log('开始播放')
      })

      innerAudioContext.onError((err) => {
        console.error('播放错误:', err)
        wx.showToast({
          title: '播放失败',
          icon: 'error'
        })
        innerAudioContext.destroy()
      })

      innerAudioContext.onEnded(() => {
        console.log('播放结束')
        innerAudioContext.destroy()
      })

      // 开始播放
      innerAudioContext.play()
    } catch (err) {
      console.error('播放失败:', err)
      wx.showToast({
        title: '播放失败',
        icon: 'error'
      })
    }
  },

  toggleExample(e) {
    this.setData({
      currentIndex: this.data.currentIndex === e.currentTarget.dataset.index ? null : e.currentTarget.dataset.index
    })
  },

  onCardMove(e) {
    if (this.moveTimer) clearTimeout(this.moveTimer)
    
    this.moveTimer = setTimeout(() => {
      const words = [...this.data.words]
      const { index } = e.currentTarget.dataset
      words[index].x = e.detail.x
      words[index].y = e.detail.y
      this.setData({ words })
    }, 16)
  }
}) 